package com.rbn.stockmobiledevices.proveedores.internal;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.rbn.stockmobiledevices.proveedores.Proveedor;
import com.rbn.stockmobiledevices.proveedores.ProveedorManager;

public class HibernateProveedorManager implements ProveedorManager {

	private SessionFactory sessionFactory;

	public HibernateProveedorManager(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public List<Proveedor> getAll() {
		return getCurrentSession().createQuery("from Proveedor").list();
	}

	@Transactional(readOnly = true)
	public Proveedor getById(Integer id) {
		return (Proveedor) getCurrentSession().load(Proveedor.class, id);
	}

	@Transactional
	public void update(Proveedor proveedor) {
		getCurrentSession().update(proveedor);
	}

	@Transactional
	public void remove(Proveedor proveedor) {
		getCurrentSession().delete(proveedor);
	}
	
	@Transactional
	public boolean remove(Integer id) {
		Proveedor p = this.getById(id);
		if(p==null)
			return false;
		getCurrentSession().delete(p);
		return true;
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Proveedor> getByNombre(String search) {
		Session session = getCurrentSession();
		String hlqQuery = "from Proveedor c";

		if (search != null && search.trim().length() > 0) {
			hlqQuery += " where nombre like '%" + search + "%'";
		}
		hlqQuery += " order by id";
		Query q = session.createQuery(hlqQuery);
		
		return q.list();

	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Proveedor> getPaginadoProveedores(int startPosition, int pageSize, String search) {
		Session session = getCurrentSession();
		String hlqQuery = "from Proveedor c";

		if (search != null && search.trim().length() > 0) {
			hlqQuery += " where nombre like '%" + search + "%'";
		}
		hlqQuery += " order by id";
		Query q = session.createQuery(hlqQuery);
		q.setFirstResult(startPosition);
		q.setMaxResults(pageSize);
				
		return q.list();
	}
	
	@Transactional(readOnly = true)
	public Proveedor getByUnicNombre(String nombre) {
		Session session = getCurrentSession();
		String hlqQuery = "from Proveedor c";
		hlqQuery += " where c.nombre = :nombre";
		hlqQuery += " order by c.nombre";
		Query q = session.createQuery(hlqQuery);
		
		q.setString("nombre", nombre);
		
		return (Proveedor)q.uniqueResult();
	}
	
	@Transactional
	public Integer save(Proveedor proveedor){
		getCurrentSession().save(proveedor);
		proveedor = getByUnicNombre(proveedor.getNombre());
		return proveedor.getId();
	}

	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
}